<template>
  <div class="maintenance-records">
    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="设备名称">
          <el-input
              v-model="searchForm.deviceName"
              placeholder="输入设备名称"
              clearable
          />
        </el-form-item>
        <el-form-item label="维护人">
          <el-input
              v-model="searchForm.maintainer"
              placeholder="输入维护人"
              clearable
          />
        </el-form-item>
        <el-form-item label="维护时间">
          <el-date-picker
              v-model="searchForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <div class="table-container">
      <el-table :data="filteredRecords" border style="width: 100%" v-loading="loading">
        <el-table-column prop="deviceName" label="设备名称" width="180" sortable />
        <el-table-column prop="faultReason" label="故障原因" width="240">
          <template #default="{ row }">
            <div class="fault-reason">{{ row.faultReason }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="maintainer" label="维护人" width="120" />
        <el-table-column prop="maintenanceTime" label="维护时间" width="180" sortable />
        <el-table-column prop="status" label="处理状态" width="120">
          <template #default="{ row }">
            <el-tag :type="statusTagType[row.status]">
              {{ statusMap[row.status] }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'

interface MaintenanceRecord {
  id: string
  deviceName: string
  faultReason: string
  maintainer: string
  maintenanceTime: string
  status: 'pending' | 'processing' | 'completed' | 'closed'
}

// 状态映射
const statusMap = {
  pending: '待处理',
  processing: '处理中',
  completed: '已完成',
  closed: '已关闭'
}

const statusTagType = {
  pending: 'warning',
  processing: 'primary',
  completed: 'success',
  closed: 'info'
}

// 模拟数据
const mockData: MaintenanceRecord[] = Array.from({ length: 45 }, (_, i) => ({
  id: `MR${String(i + 1).padStart(4, '0')}`,
  deviceName: `设备-${i % 10 + 1}`,
  faultReason: ['电路故障', '机械故障', '软件异常', '参数异常'][i % 4],
  maintainer: ['张三', '李四', '王五'][i % 3],
  maintenanceTime: `2023-${String((i % 12) + 1).padStart(2, '0')}-${String((i % 28) + 1).padStart(2, '0')}`,
  status: ['pending', 'processing', 'completed', 'closed'][i % 4] as any
}))

// 搜索表单
const searchForm = reactive({
  deviceName: '',
  maintainer: '',
  dateRange: []
})

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 加载状态
const loading = ref(false)
const allRecords = ref<MaintenanceRecord[]>([])

// 过滤后的记录
const filteredRecords = computed(() => {
  return allRecords.value
      .filter(record => {
        const matchesDevice = record.deviceName.includes(searchForm.deviceName)
        const matchesMaintainer = record.maintainer.includes(searchForm.maintainer)
        const [start, end] = searchForm.dateRange || []
        const matchesDate = start && end
            ? new Date(record.maintenanceTime) >= new Date(start) &&
            new Date(record.maintenanceTime) <= new Date(end)
            : true
        return matchesDevice && matchesMaintainer && matchesDate
      })
      .slice(
          (pagination.currentPage - 1) * pagination.pageSize,
          pagination.currentPage * pagination.pageSize
      )
})

// 初始化数据
onMounted(() => {
  loading.value = true
  setTimeout(() => {
    allRecords.value = mockData
    pagination.total = mockData.length
    loading.value = false
  }, 500)
})

// 处理查询
const handleSearch = () => {
  pagination.currentPage = 1
  updatePaginationTotal()
}

// 重置查询
const resetSearch = () => {
  searchForm.deviceName = ''
  searchForm.maintainer = ''
  searchForm.dateRange = []
  handleSearch()
}

// 更新分页总数
const updatePaginationTotal = () => {
  pagination.total = allRecords.value.filter(record => {
    const [start, end] = searchForm.dateRange || []
    const dateMatch = start && end
        ? new Date(record.maintenanceTime) >= new Date(start) &&
        new Date(record.maintenanceTime) <= new Date(end)
        : true
    return record.deviceName.includes(searchForm.deviceName) &&
        record.maintainer.includes(searchForm.maintainer) &&
        dateMatch
  }).length
}

// 处理分页变化
const handleSizeChange = (val: number) => {
  pagination.pageSize = val
  updatePaginationTotal()
}

const handleCurrentChange = (val: number) => {
  pagination.currentPage = val
}
</script>

<style scoped>
.maintenance-records {
  padding: 20px;
}

.search-container {
  background-color: #f5f7fa;
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 4px;
}

.table-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.fault-reason {
  white-space: pre-wrap;
  word-break: break-word;
}
</style>